<template>
  <div class="seckill-manager">
    <!-- 数据统计卡片 -->
    <div class="statistics-container">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="statistics-card">
            <template #header>
              <div class="card-header">
                <span>秒杀活动总数</span>
              </div>
            </template>
            <div class="statistics-value">
              <span class="number">{{ statistics.total }}</span>
              <span class="label">个活动</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="statistics-card">
            <template #header>
              <div class="card-header">
                <span>进行中活动</span>
              </div>
            </template>
            <div class="statistics-value">
              <span class="number success">{{ statistics.running }}</span>
              <span class="label">个活动</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="statistics-card">
            <template #header>
              <div class="card-header">
                <span>已结束活动</span>
              </div>
            </template>
            <div class="statistics-value">
              <span class="number danger">{{ statistics.ended }}</span>
              <span class="label">个活动</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="statistics-card">
            <template #header>
              <div class="card-header">
                <span>已预热活动</span>
              </div>
            </template>
            <div class="statistics-value">
              <span class="number warning">{{ statistics.warmedUp }}</span>
              <span class="label">个活动</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <el-card class="filter-container">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="活动名称">
          <el-input v-model="queryParams.name" placeholder="请输入活动名称" clearable />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="queryParams.productName" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="活动状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="未开始" value="0" />
            <el-option label="进行中" value="1" />
            <el-option label="已结束" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="list-container">
      <template #header>
        <div class="card-header">
          <span>秒杀活动列表</span>
          <el-button type="primary" @click="handleAdd">新增秒杀活动</el-button>
        </div>
      </template>
      
      <el-table 
        v-loading="loading" 
        :data="seckillList" 
        style="width: 100%"
        height="calc(100vh - 300px)"
        :header-cell-style="{ background: '#f5f7fa' }"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="productName" label="商品名称" />
        <el-table-column prop="originalPrice" label="原价" width="100">
          <template #default="scope">
            ¥{{ scope.row.originalPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="seckillPrice" label="秒杀价" width="100">
          <template #default="scope">
            ¥{{ scope.row.seckillPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100" />
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getActivityStatus(scope.row).type">
              {{ getActivityStatus(scope.row).text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="预热状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isWarmedUp ? 'success' : 'warning'">
              {{ scope.row.isWarmedUp ? '已预热' : '未预热' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button 
                size="small" 
                type="success" 
                @click="handleWarmUp(scope.row)"
                :disabled="scope.row.isWarmedUp || getActivityStatus(scope.row).type === 'danger'"
              >
                预热
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDelete(scope.row)"
                :disabled="scope.row.isWarmedUp"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑秒杀活动弹窗 -->
    <el-dialog
      :title="form.id ? '编辑秒杀活动' : '新增秒杀活动'"
      v-model="dialogVisible"
      width="500px"
      @closed="handleDialogClosed"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="商品" prop="productId">
          <el-select v-model="form.productId" placeholder="请选择商品">
            <el-option
              v-for="item in productList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="秒杀价格" prop="seckillPrice">
          <el-input-number v-model="form.seckillPrice" :precision="2" :step="0.1" :min="0" />
        </el-form-item>
        <el-form-item label="秒杀库存" prop="stock">
          <el-input-number v-model="form.stock" :min="1" />
        </el-form-item>
        <el-form-item label="活动时间" prop="timeRange">
          <el-date-picker
            v-model="form.timeRange"
            type="datetimerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="dateShortcuts"
            :locale="zhCn"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'

// 模拟商品数据
const productList = ref([
  { id: 1, name: 'iPhone 15', price: 5999 },
  { id: 2, name: 'MacBook Pro', price: 12999 }
])

// 模拟秒杀活动数据
const seckillList = ref([
  {
    id: 1,
    name: 'iPhone 15 限时秒杀',
    productId: 1,
    productName: 'iPhone 15',
    originalPrice: 5999,
    seckillPrice: 4999,
    stock: 100,
    startTime: '2024-01-20 10:00:00',
    endTime: '2024-01-20 22:00:00',
    isWarmedUp: false
  }
])

const dialogVisible = ref(false)
const formRef = ref(null)
const timeRange = ref([])

// 表单数据
const form = reactive({
  id: null,
  name: '',
  productId: null,
  seckillPrice: 0,
  stock: 0,
  timeRange: [], // 修改这里，将时间范围作为表单的一部分
  startTime: '',
  endTime: ''
})

// 表单校验规则修改
const rules = {
  name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  productId: [{ required: true, message: '请选择商品', trigger: 'change' }],
  seckillPrice: [{ required: true, message: '请输入秒杀价格', trigger: 'change' }],
  stock: [{ required: true, message: '请输入秒杀库存', trigger: 'change' }],
  timeRange: [{ required: true, message: '请选择活动时间', trigger: 'change' }]
}

// 日期快捷选项
const dateShortcuts = [
  {
    text: '今天',
    value: () => {
      const start = new Date()
      start.setHours(0, 0, 0, 0)
      const end = new Date()
      end.setHours(23, 59, 59, 999)
      return [start, end]
    }
  },
  {
    text: '明天',
    value: () => {
      const start = new Date()
      start.setDate(start.getDate() + 1)
      start.setHours(0, 0, 0, 0)
      const end = new Date(start)
      end.setHours(23, 59, 59, 999)
      return [start, end]
    }
  }
]

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  productName: '',
  status: ''
})

const loading = ref(false)
const total = ref(0)

// 统计数据
const statistics = reactive({
  total: 0,
  running: 0,
  ended: 0,
  warmedUp: 0
})

// 更新统计数据
const updateStatistics = () => {
  const now = new Date().getTime()
  statistics.total = seckillList.value.length
  statistics.running = seckillList.value.filter(item => 
    now >= new Date(item.startTime).getTime() && 
    now <= new Date(item.endTime).getTime()
  ).length
  statistics.ended = seckillList.value.filter(item => 
    now > new Date(item.endTime).getTime()
  ).length
  statistics.warmedUp = seckillList.value.filter(item => 
    item.isWarmedUp
  ).length
}

// 监听列表变化，更新统计数据
watch(seckillList, () => {
  updateStatistics()
}, { deep: true, immediate: true })

// 查询方法
const handleQuery = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    loading.value = false
    updateStatistics()
  }, 500)
}

// 重置查询
const resetQuery = () => {
  queryParams.name = ''
  queryParams.productName = ''
  queryParams.status = ''
  handleQuery()
}

// 分页方法
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  handleQuery()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  handleQuery()
}

// 新增秒杀活动
const handleAdd = () => {
  form.id = null
  form.name = ''
  form.productId = null
  form.seckillPrice = 0
  form.stock = 0
  form.timeRange = []
  dialogVisible.value = true
}

// 编辑秒杀活动
const handleEdit = (row) => {
  Object.assign(form, {
    id: row.id,
    name: row.name,
    productId: row.productId,
    seckillPrice: row.seckillPrice,
    stock: row.stock,
    timeRange: [row.startTime, row.endTime] // 修改这里，设置时间范围
  })
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async (formEl) => {
  if (!formEl) return
  
  try {
    await formEl.validate()
    
    // 设置活动时间
    if (form.timeRange?.length === 2) {
      form.startTime = form.timeRange[0]
      form.endTime = form.timeRange[1]
    }

    // 模拟提交
    const product = productList.value.find(p => p.id === form.productId)
    const seckillData = {
      ...form,
      productName: product?.name,
      originalPrice: product?.price,
      isWarmedUp: false
    }

    if (form.id) {
      const index = seckillList.value.findIndex(item => item.id === form.id)
      if (index !== -1) {
        seckillList.value[index] = { ...seckillList.value[index], ...seckillData }
      }
      ElMessage.success('编辑成功')
    } else {
      seckillData.id = seckillList.value.length + 1
      seckillList.value.push(seckillData)
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 删除秒杀活动
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该秒杀活动吗？', '提示', {
      type: 'warning'
    })
    const index = seckillList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      seckillList.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  } catch {
    // 取消删除
  }
}

// 预热操作
const handleWarmUp = async (row) => {
  try {
    await ElMessageBox.confirm(
      '预热操作会将秒杀活动信息加载到Redis中，确定要执行吗？',
      '预热确认',
      {
        type: 'warning',
        confirmButtonText: '确定预热',
        cancelButtonText: '取消'
      }
    )
    
    loading.value = true
    // 模拟预热操作
    setTimeout(() => {
      row.isWarmedUp = true
      loading.value = false
      ElMessage.success('预热成功')
    }, 1000)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('预热失败')
    }
  }
}

// 获取活动状态
const getActivityStatus = (row) => {
  const now = new Date().getTime()
  const start = new Date(row.startTime).getTime()
  const end = new Date(row.endTime).getTime()

  if (now < start) {
    return { type: 'info', text: '未开始' }
  } else if (now > end) {
    return { type: 'danger', text: '已结束' }
  } else {
    return { type: 'success', text: '进行中' }
  }
}
</script>

<style lang="scss" scoped>
.seckill-manager {
  height: 100%;

  .statistics-container {
    margin-bottom: 20px;

    .statistics-card {
      .card-header {
        display: flex;
        align-items: center;
        font-size: 14px;
        color: #606266;
      }

      .statistics-value {
        display: flex;
        align-items: baseline;
        padding: 10px 0;

        .number {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
          margin-right: 8px;

          &.success {
            color: #67c23a;
          }

          &.danger {
            color: #f56c6c;
          }

          &.warning {
            color: #e6a23c;
          }
        }

        .label {
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }

  .filter-container {
    margin-bottom: 20px;
  }

  .list-container {
    height: calc(100vh - 180px);
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    :deep(.el-table) {
      max-height: calc(100vh - 300px);
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    padding: 10px 0;
  }

  :deep(.el-card__header) {
    padding: 15px 20px;
  }

  :deep(.el-card__body) {
    padding: 10px 20px;
  }
}
</style>